package com.andyliu.system.controller;


import com.andyliu.Constants;
import com.andyliu.common.ResponseResult;
import com.andyliu.controller.BaseController;
import com.andyliu.interceptor.BusinessType;
import com.andyliu.log.Log;
import com.andyliu.system.dto.UserDto;
import com.andyliu.system.entity.User;
import com.andyliu.system.entity.UserRole;
import com.andyliu.system.service.IUserRoleService;
import com.andyliu.system.service.IUserService;
import com.andyliu.vo.PageVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author andyLiu
 * @since 2021-08-10
 */
@Slf4j
@Controller
@RequestMapping("/system/user")
@Api(value = "用户信息表控制器", tags = "用户信息表操作接口")
public class UserController extends BaseController {
    @Autowired
    private IUserService service;

    @Autowired
    private IUserRoleService userRoleService;

    /**
     * 跳转到列表页
     */
    @GetMapping()
    @ApiIgnore
    public String toData() {
        log.debug("跳转到列表页");
        return "system/User/data";
    }

    /**
     * 异步加载分页数据
     */
    @PostMapping("data")
    @ResponseBody
    @ApiOperation(value = "用户信息表分页数据接口", notes = "根据查询和分页条件返回分页数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNumber", value = "分页页码", required = true, type = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示个数", required = true, type = "Integer"),
            @ApiImplicitParam(name = "obj", value = "用于分装实体的查询条件", required = false)
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常"),
            @ApiResponse(code = 501, message = "权限不足")
    })
    @Log(moduleName = "用户分页数据", businessType = BusinessType.QUERY)
    public ResponseResult data(User obj, @RequestParam(required = true, defaultValue = "1") Integer pageNumber, @RequestParam(required = true, defaultValue = Constants.DEFAULT_PAGE_SIZE) Integer pageSize) {
        log.debug("分页查询User数据");
        PageVO pageVO = startPage();
        IPage<UserDto> page = service.selectByPage(pageVO.getPageNumber(), pageVO.getPageSize(), obj);
        return ResponseResult.success(page);
    }

    /**
     * 跳转到新增编辑页面
     */
    @GetMapping("/edit/{id}")
    @ApiIgnore
    @Log(moduleName = "用户详情获取", businessType = BusinessType.QUERY)
    public String toEidt(@PathVariable Integer id, ModelMap mmap) {
        if (id != -1) {
            User user = service.getById(id);
            mmap.put("user", user);
        }
        return "system/User/edit";
    }

    @GetMapping("/info/{id}")
    @ResponseBody
    @ApiOperation(value = "根据主键获取用户信息表数据接口", notes = "根据主键获取实体数据", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true, type = "Integer")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常"),
            @ApiResponse(code = 501, message = "权限不足")
    })
    public ResponseResult toEidt(@PathVariable Integer id) {
        log.debug("查看用户信息表的数据,id为" + id);
        UserDto obj = service.queryUserById(id);
        return ResponseResult.success(obj);
    }

    /**
     * 异步保存或新增
     */
    @PostMapping("save")
    @ResponseBody
    @ApiOperation(value = "保存或更新用户信息表数据接口", notes = "如果实体类中有主键为更新，否则为保存", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户信息表实体", required = true, type = "Integer")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常"),
            @ApiResponse(code = 501, message = "权限不足")
    })
    @Log(moduleName = "用户信息保存", businessType = BusinessType.INSERT)
    public ResponseResult save(@RequestBody User user) {
        log.debug("保存用户信息表的数据");
        Subject subject = SecurityUtils.getSubject();
        String userName = subject.getPrincipal().toString();
        UserRole userRole = new UserRole();
        if (user.getUserId() != null) {
            user.setUpdateBy(userName);
            user.setUpdateTime(LocalDateTime.now());
            if(StringUtils.isNotEmpty(user.getPassword())){
               String pwd = new SimpleHash("MD5", user.getPassword(), user.getLoginName(), 1024).toString();
                user.setPassword(pwd);
            }
            boolean status = service.updateById(user);
            if (status) {
                return ResponseResult.success();
            } else {
                return ResponseResult.error();
            }
        }
        user.setCreateBy(userName);
        user.setCreateTime(LocalDateTime.now());

        return service.save(user) == true ?
                ResponseResult.success()
                : ResponseResult.error();
    }

    /**
     * 删除或批量删除请求
     */
    @DeleteMapping("delete")
    @ResponseBody
    @ApiOperation(value = "批量删除用户信息表数据接口", notes = "批量删除", httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "需要删除的主键的数组", required = true, type = "Integer")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常"),
            @ApiResponse(code = 501, message = "权限不足")
    })
    @Log(moduleName = "用户数据删除", businessType = BusinessType.DELETE)
    public ResponseResult delete(Integer[] ids) {
        log.debug("删除用户信息表的数据,id为" + ids);
        return service.removeByIds(Arrays.asList(ids))==true?ResponseResult.success():ResponseResult.error();
    }

    /**
     * 单个删除
     */
    @DeleteMapping("delete/{id}")
    @ResponseBody
    @ApiOperation(value = "删除用户信息表数据接口", notes = "单个删除，根据主键删除", httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "需要删除主键", required = true, type = "Integer")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 500, message = "服务器内部异常"),
            @ApiResponse(code = 501, message = "权限不足")
    })
    @Log(moduleName = "用户数据删除", businessType = BusinessType.DELETE)
    public ResponseResult delete(@PathVariable Integer id) {
        log.debug("删除用户信息表的数据,id为" + id);
        return service.removeById(id)==true?ResponseResult.success():ResponseResult.error();
    }

    @GetMapping("profile")
    public String toProfile(){
        return "system/User/profile/profile";
    }
    @GetMapping("resetPwd")
    public String toRestPwd(){
        return "system/User/profile/resetPwd";
    }

    /**
     * 获取登录用户信息
     */
    @GetMapping("/userInfo")
    @ResponseBody
    public ResponseResult loginUserInfo()
    {
        Subject subject = SecurityUtils.getSubject();
        String loginName = subject.getPrincipal().toString();
        User user = service.getUserByLoginName(loginName);
        UserDto userDto = service.queryUserById(user.getUserId().intValue());
        return ResponseResult.success(userDto);
    }

    @GetMapping("profile/checkPassword")
    @ResponseBody
    public boolean checkPassword(String oldPassword){
        Subject subject = SecurityUtils.getSubject();
        String loginName = subject.getPrincipal().toString();
        User user = service.getUserByLoginName(loginName);
        boolean status = service.passwordMismatch(oldPassword,user);
        return status;
    }

}


